"""
用户认证视图
"""
from rest_framework import generics, status, permissions, viewsets
from rest_framework.decorators import api_view, permission_classes, action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.token_blacklist.models import BlacklistedToken, OutstandingToken
from rest_framework_simplejwt.views import TokenObtainPairView
from django.contrib.auth import login
from django.utils import timezone
from django.db.models import Q
from .models import User, LoginLog, Permission, RolePermission
from .serializers import (
    UserSerializer, UserProfileSerializer, LoginSerializer,
    ChangePasswordSerializer, LoginLogSerializer, PermissionSerializer,
    RolePermissionSerializer, RegisterSerializer
)
from .permissions import IsAdminUser, IsTeacherOrAdmin
from .utils import get_client_ip, get_user_agent


class CustomTokenObtainPairView(TokenObtainPairView):
    """自定义JWT登录视图"""
    
    def post(self, request, *args, **kwargs):
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data['user']
            
            # 记录登录日志
            LoginLog.objects.create(
                user=user,
                ip_address=get_client_ip(request),
                user_agent=get_user_agent(request),
                is_success=True
            )
            
            # 更新最后登录信息
            user.last_login = timezone.now()
            user.last_login_ip = get_client_ip(request)
            user.save(update_fields=['last_login', 'last_login_ip'])
            
            # 生成JWT token
            refresh = RefreshToken.for_user(user)
            
            return Response({
                'refresh': str(refresh),
                'access': str(refresh.access_token),
                'user': UserProfileSerializer(user).data
            })
        else:
            # 记录登录失败日志
            username = request.data.get('username')
            if username:
                try:
                    user = User.objects.get(username=username)
                    LoginLog.objects.create(
                        user=user,
                        ip_address=get_client_ip(request),
                        user_agent=get_user_agent(request),
                        is_success=False,
                        failure_reason=str(serializer.errors)
                    )
                except User.DoesNotExist:
                    pass
            
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def register(request):
    """用户注册"""
    serializer = RegisterSerializer(data=request.data)
    if serializer.is_valid():
        user = serializer.save()
        return Response({
            'message': '注册成功',
            'user': UserProfileSerializer(user).data
        }, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
def logout(request):
    """用户登出"""
    try:
        refresh_token = request.data.get('refresh')
        if refresh_token:
            token = RefreshToken(refresh_token)
            token.blacklist()
        return Response({'message': '登出成功'})
    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
def profile(request):
    """获取用户资料"""
    serializer = UserProfileSerializer(request.user)
    return Response(serializer.data)


@api_view(['PUT'])
def update_profile(request):
    """更新用户资料"""
    serializer = UserProfileSerializer(request.user, data=request.data, partial=True)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
def change_password(request):
    """修改密码"""
    serializer = ChangePasswordSerializer(data=request.data, context={'request': request})
    if serializer.is_valid():
        user = request.user
        user.set_password(serializer.validated_data['new_password'])
        user.save()
        return Response({'message': '密码修改成功'})
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class UserListCreateView(generics.ListCreateAPIView):
    """用户列表和创建"""
    
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [IsAdminUser]
    filterset_fields = ['role', 'is_active']
    search_fields = ['username', 'email', 'first_name', 'last_name']
    ordering_fields = ['date_joined', 'last_login']
    ordering = ['-date_joined']


class UserDetailView(generics.RetrieveUpdateDestroyAPIView):
    """用户详情、更新和删除"""
    
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [IsAdminUser]


class LoginLogListView(generics.ListAPIView):
    """登录日志列表"""
    
    serializer_class = LoginLogSerializer
    permission_classes = [IsTeacherOrAdmin]
    filterset_fields = ['user', 'is_success']
    search_fields = ['user__username', 'ip_address']
    ordering_fields = ['login_time']
    ordering = ['-login_time']
    
    def get_queryset(self):
        user = self.request.user
        if user.is_admin:
            return LoginLog.objects.all()
        elif user.is_teacher:
            # 老师只能查看自己的登录日志
            return LoginLog.objects.filter(user=user)
        else:
            # 学生只能查看自己的登录日志
            return LoginLog.objects.filter(user=user)


class PermissionListCreateView(generics.ListCreateAPIView):
    """权限列表和创建"""
    
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer
    permission_classes = [IsAdminUser]
    filterset_fields = ['module']
    search_fields = ['name', 'codename', 'description']
    ordering_fields = ['created_at']
    ordering = ['module', 'name']


class PermissionDetailView(generics.RetrieveUpdateDestroyAPIView):
    """权限详情、更新和删除"""
    
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer
    permission_classes = [IsAdminUser]


class RolePermissionListCreateView(generics.ListCreateAPIView):
    """角色权限列表和创建"""
    
    queryset = RolePermission.objects.all()
    serializer_class = RolePermissionSerializer
    permission_classes = [IsAdminUser]
    filterset_fields = ['role']
    ordering = ['role', 'permission__module', 'permission__name']


class RolePermissionDetailView(generics.RetrieveUpdateDestroyAPIView):
    """角色权限详情、更新和删除"""
    
    queryset = RolePermission.objects.all()
    serializer_class = RolePermissionSerializer
    permission_classes = [IsAdminUser]


@api_view(['GET'])
@permission_classes([IsAdminUser])
def user_statistics(request):
    """用户统计"""
    total_users = User.objects.count()
    admin_count = User.objects.filter(role='admin').count()
    teacher_count = User.objects.filter(role='teacher').count()
    student_count = User.objects.filter(role='student').count()
    active_users = User.objects.filter(is_active=True).count()
    
    return Response({
        'total_users': total_users,
        'admin_count': admin_count,
        'teacher_count': teacher_count,
        'student_count': student_count,
        'active_users': active_users,
        'inactive_users': total_users - active_users
    })


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def user_permissions(request):
    """获取当前用户权限"""
    try:
        user = request.user

        # 检查用户是否已认证
        if not user.is_authenticated:
            return Response(
                {'error': '用户未认证'},
                status=status.HTTP_401_UNAUTHORIZED
            )

        # 获取用户权限
        try:
            permissions = RolePermission.objects.filter(role=user.role).select_related('permission')
            permission_list = [rp.permission.codename for rp in permissions]
        except Exception as e:
            # 如果权限表不存在或查询失败，返回基础权限
            permission_list = []

        return Response({
            'role': user.role,
            'permissions': permission_list,
            'user_id': user.id,
            'username': user.username
        })

    except Exception as e:
        return Response(
            {'error': f'获取权限失败: {str(e)}'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


class PersonalCenterViewSet(viewsets.ViewSet):
    """个人中心ViewSet"""

    permission_classes = [permissions.IsAuthenticated]

    @action(detail=False, methods=['get'])
    def profile(self, request):
        """获取个人资料"""
        serializer = UserProfileSerializer(request.user)
        return Response(serializer.data)

    @action(detail=False, methods=['put'])
    def update_profile(self, request):
        """更新个人资料"""
        serializer = UserProfileSerializer(request.user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'message': '个人资料更新成功',
                'data': serializer.data
            })
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=['post'])
    def change_password(self, request):
        """修改密码"""
        serializer = ChangePasswordSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            user = request.user
            user.set_password(serializer.validated_data['new_password'])
            user.save()
            return Response({'message': '密码修改成功'})
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=['get'])
    def login_history(self, request):
        """获取登录历史"""
        logs = LoginLog.objects.filter(user=request.user).order_by('-login_time')[:20]
        serializer = LoginLogSerializer(logs, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取个人统计信息"""
        user = request.user

        # 基础统计
        stats = {
            'total_logins': LoginLog.objects.filter(user=user).count(),
            'last_login': user.last_login,
            'date_joined': user.date_joined,
            'role': user.get_role_display(),
            'is_active': user.is_active,
        }

        # 根据角色添加特定统计
        if user.role == 'student':
            # 学生相关统计
            from students.models import Student
            try:
                student = Student.objects.get(id=user.id)
                stats.update({
                    'student_id': student.student_id,
                    'grade': student.grade.name if student.grade else None,
                    'status': student.get_status_display(),
                    'employment_status': student.get_employment_status_display(),
                    'resume_status': student.get_resume_status_display(),
                })
            except Student.DoesNotExist:
                pass

        elif user.role == 'teacher':
            # 老师相关统计
            from students.models import Student
            supervised_students = Student.objects.filter(advisor=user).count()
            stats.update({
                'supervised_students': supervised_students,
            })

        return Response(stats)

    @action(detail=False, methods=['get'])
    def preferences(self, request):
        """获取个人偏好设置"""
        user = request.user

        # 从用户模型或单独的偏好设置表获取设置
        # 这里使用默认设置，实际项目中可以存储在数据库中
        preferences = {
            'theme': 'light',
            'language': 'zh-CN',
            'timezone': 'Asia/Shanghai',
            'emailNotifications': True,
            'desktopNotifications': False,
            'autoSave': True,
            'pageSize': 20
        }

        return Response(preferences)

    @action(detail=False, methods=['post'])
    def save_preferences(self, request):
        """保存个人偏好设置"""
        user = request.user
        preferences_data = request.data

        # 这里可以将偏好设置保存到数据库
        # 目前只是验证数据格式
        allowed_themes = ['light', 'dark', 'auto']
        allowed_languages = ['zh-CN', 'en-US']
        allowed_timezones = ['Asia/Shanghai', 'Asia/Tokyo', 'America/New_York']

        if preferences_data.get('theme') not in allowed_themes:
            return Response({'error': '无效的主题设置'}, status=status.HTTP_400_BAD_REQUEST)

        if preferences_data.get('language') not in allowed_languages:
            return Response({'error': '无效的语言设置'}, status=status.HTTP_400_BAD_REQUEST)

        if preferences_data.get('timezone') not in allowed_timezones:
            return Response({'error': '无效的时区设置'}, status=status.HTTP_400_BAD_REQUEST)

        # 实际项目中在这里保存到数据库
        # UserPreferences.objects.update_or_create(
        #     user=user,
        #     defaults=preferences_data
        # )

        return Response({'message': '偏好设置保存成功'})


class SystemSettingsViewSet(viewsets.ViewSet):
    """系统设置ViewSet"""

    permission_classes = [IsAdminUser]

    @action(detail=False, methods=['get'])
    def system_info(self, request):
        """获取系统信息"""
        import platform
        import sys
        from django import get_version
        from django.conf import settings

        # 确保所有值都是可序列化的
        db_name = settings.DATABASES['default']['NAME']
        if hasattr(db_name, '__str__'):
            db_name = str(db_name)

        system_info = {
            'system': {
                'platform': platform.platform(),
                'python_version': sys.version,
                'django_version': get_version(),
                'debug_mode': settings.DEBUG,
            },
            'database': {
                'engine': settings.DATABASES['default']['ENGINE'],
                'name': db_name,
            },
            'application': {
                'name': '鸥鹏超级面试官',
                'version': '1.0.0',
                'description': '智能面试管理系统',
            }
        }

        return Response(system_info)

    @action(detail=False, methods=['get'])
    def user_statistics(self, request):
        """获取用户统计"""
        from django.db.models import Count

        user_stats = User.objects.values('role').annotate(count=Count('id'))
        total_users = User.objects.count()
        active_users = User.objects.filter(is_active=True).count()

        stats = {
            'total_users': total_users,
            'active_users': active_users,
            'inactive_users': total_users - active_users,
            'by_role': {item['role']: item['count'] for item in user_stats}
        }

        return Response(stats)

    @action(detail=False, methods=['get'])
    def student_statistics(self, request):
        """获取学生统计"""
        from students.models import Student, Grade
        from django.db.models import Count

        total_students = Student.objects.count()

        # 按状态统计
        status_stats = Student.objects.values('status').annotate(count=Count('id'))

        # 按就业状态统计
        employment_stats = Student.objects.values('employment_status').annotate(count=Count('id'))

        # 按年级统计
        grade_stats = Student.objects.values('grade__name').annotate(count=Count('id'))

        stats = {
            'total_students': total_students,
            'by_status': {item['status']: item['count'] for item in status_stats},
            'by_employment': {item['employment_status']: item['count'] for item in employment_stats},
            'by_grade': {item['grade__name']: item['count'] for item in grade_stats if item['grade__name']}
        }

        return Response(stats)

    @action(detail=False, methods=['get'])
    def login_statistics(self, request):
        """获取登录统计"""
        from django.utils import timezone
        from datetime import timedelta
        from django.db.models import Count

        now = timezone.now()

        # 今日登录
        today_logins = LoginLog.objects.filter(
            login_time__date=now.date()
        ).count()

        # 本周登录
        week_ago = now - timedelta(days=7)
        week_logins = LoginLog.objects.filter(
            login_time__gte=week_ago
        ).count()

        # 本月登录
        month_ago = now - timedelta(days=30)
        month_logins = LoginLog.objects.filter(
            login_time__gte=month_ago
        ).count()

        # 按日期统计最近7天
        daily_stats = []
        for i in range(7):
            date = (now - timedelta(days=i)).date()
            count = LoginLog.objects.filter(login_time__date=date).count()
            daily_stats.append({
                'date': date.strftime('%Y-%m-%d'),
                'count': count
            })

        stats = {
            'today_logins': today_logins,
            'week_logins': week_logins,
            'month_logins': month_logins,
            'daily_stats': daily_stats
        }

        return Response(stats)

    @action(detail=False, methods=['post'])
    def clear_logs(self, request):
        """清理日志"""
        days = request.data.get('days', 30)

        from django.utils import timezone
        from datetime import timedelta

        cutoff_date = timezone.now() - timedelta(days=days)
        deleted_count = LoginLog.objects.filter(login_time__lt=cutoff_date).delete()[0]

        return Response({
            'message': f'成功清理 {deleted_count} 条登录日志',
            'deleted_count': deleted_count
        })

    @action(detail=False, methods=['get'])
    def backup_info(self, request):
        """获取备份信息"""
        import os
        from django.conf import settings

        # 这里可以添加实际的备份逻辑
        backup_info = {
            'last_backup': None,
            'backup_size': 0,
            'backup_location': 'Not configured',
            'auto_backup_enabled': False,
        }

        return Response(backup_info)
